package org.alps.demo.juc.bio;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @date 2021-06-01
 * @author zkw
 */
public class SocketServer {
    public static void main(String[] args) throws IOException {
        ServerSocket serverSocket = new ServerSocket(9000);
        while (true) {
            System.out.println("等待连接...");
            //阻塞方法
            Socket socket = serverSocket.accept();
            /**
             * 客户端通过cmd窗口建立连接：telnet localhost 9000
             * 按 ctrl+]，调到输入窗口
             */
            System.out.println("有客户端连接了...");
            handler(socket);
        }
    }

    private static void handler(Socket socket) throws IOException {
        byte[] bytes = new byte[1024];
        System.out.println("准备read...");
        int read = socket.getInputStream().read(bytes);
        //telnet 输入 help帮助命令，输入: send hello
        System.out.println("read完毕...");
        if (read!=-1) {
            System.out.println("接收到客户端的数据：" + new String(bytes, 0, read));
        }
    }
}
